package com.hanlink.dsp.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.SPUtils;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.qztech.sdk.ui.widget.ClickableCheckBox;
import com.qztech.utils.YzDebug;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

//import butterknife.BindView;
//import butterknife.BindViews;
//import butterknife.ButterKnife;

import static com.hanlink.dsp.util.DataUtil.KEY_CHANNEL_NAME;
import static com.hanlink.dsp.util.DataUtil.KEY_INPUT;

/**
 * Carate By YangZhong
 */
public class SummingChannelLayout extends LinearLayout implements View.OnClickListener, View.OnLongClickListener {

    private Button ch_btns_1,ch_btns_2,ch_btns_3,ch_btns_4,ch_btns_5,ch_btns_6,ch_btns_7,ch_btns_8;

    //@BindViews({R.id.ch_btns_1, R.id.ch_btns_2, R.id.ch_btns_3, R.id.ch_btns_4, R.id.ch_btns_5, R.id.ch_btns_6, R.id.ch_btns_7, R.id.ch_btns_8})
    List<Button> mButtons;

    //@BindView(R.id.input)
    ClickableCheckBox mBtnInput;


    //@BindView(R.id.output)
    ClickableCheckBox mBtnOutput;
    //@BindView(R.id.ch_name)
    ClickableCheckBox mBtnCH;
    private String mChName = "-";
    private Paint mPaint;
    private float mLineWidth = 2f;
    private int mLineColor = Color.BLACK;
    private Set<Integer> mChsets = new HashSet<>();
    private int mChannel;
    private boolean isFixed = false;//2ch 4ch时不可调节
    public SummingChannelLayout(Context context) {
        this(context, null);
    }

    public SummingChannelLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SummingChannelLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    private void init(Context context, @Nullable AttributeSet attrs) {
        setOrientation(VERTICAL);
       View view =  LayoutInflater.from(context).inflate(R.layout.summing_channel_layout, this, true);
       // ButterKnife.bind(this, this);
        ch_btns_1 = view.findViewById(R.id.ch_btns_1);
        ch_btns_2 = view.findViewById(R.id.ch_btns_2);
        ch_btns_3 = view.findViewById(R.id.ch_btns_3);
        ch_btns_4 = view.findViewById(R.id.ch_btns_4);
        ch_btns_5 = view.findViewById(R.id.ch_btns_5);
        ch_btns_6 = view.findViewById(R.id.ch_btns_6);
        ch_btns_7 = view.findViewById(R.id.ch_btns_7);
        ch_btns_8 = view.findViewById(R.id.ch_btns_8);
        mButtons = new ArrayList<>();
        mButtons.add(ch_btns_1);
        mButtons.add(ch_btns_2);
        mButtons.add(ch_btns_3);
        mButtons.add(ch_btns_4);
        mButtons.add(ch_btns_5);
        mButtons.add(ch_btns_6);
        mButtons.add(ch_btns_7);
        mButtons.add(ch_btns_8);
        mBtnInput = view.findViewById(R.id.input);
        mBtnOutput = view.findViewById(R.id.output);
        mBtnCH = view.findViewById(R.id.ch_name);



        mPaint = new Paint();
        mPaint.setColor(mLineColor);
        mPaint.setStrokeWidth(mLineWidth);
        for (Button button : mButtons) {
            button.setOnClickListener(this);
        }
//        mBtnInput.setOnClickListener(this);
        mBtnInput.setOnLongClickListener(this);
        mBtnCH.setOnClickListener(this);
        mBtnOutput.setOnClickListener(this);


        if (attrs == null) return;
        final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SummingChannelLayout);
        mChName =  array.getString(R.styleable.SummingChannelLayout_scl_channel_name);
        array.recycle();


    }
    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()){
            case R.id.input:
                ViewUtil.showChangeInputDialog(getContext(), mChannel, name -> mBtnInput.setText(name));
                break;
        }
        return true;
    }
    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            switch (v.getId()){
                case R.id.output:
                    if (isFixed)return;
                    setChecked(!isChecked);
                    if (mOnSummingChannelListener != null){
                        mOnSummingChannelListener.onOutputChange(mChannel, isChecked);
                    }
                    break;
                case R.id.ch_name:
                    if (isChecked){
                        ViewUtil.showChangeChannelNameDialog(getContext(), mChannel, name -> setChannelName(name));
                    }else{
                        if (isFixed)return;
                        setChecked(true);
                        if (mOnSummingChannelListener != null){
                            mOnSummingChannelListener.onOutputChange(mChannel, isChecked);
                        }
                    }
                    break;

                default:{
                    if (isFixed)return;
                    final Button b = (Button) v;
                    int index = -1;
                    try {
                        index = Integer.parseInt((String) b.getText()) -1;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (index != -1) {
                        if (mChsets.contains(index)) {
                            mChsets.remove(index);
                            b.setSelected(false);
                            if (mOnSummingChannelListener != null)
                                mOnSummingChannelListener.onInputChanged(mChannel, index, false);
                        } else {
                            mChsets.add(index);
                            b.setSelected(true);
                            if (mOnSummingChannelListener != null)
                                mOnSummingChannelListener.onInputChanged(mChannel, index, true);
                        }
                    }
                }
                break;
            }

        }
    }


    private boolean isChecked = false;

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        YzDebug.d("setChecked----------------"+ checked);
        isChecked = checked;
        for (Button button : mButtons) {
            button.setEnabled(checked);
        }
        mBtnInput.setChecked(checked);
        mBtnCH.setChecked(checked);
        mBtnOutput.setChecked(checked);
    }

    public void addSum(int num){
        if (mChsets.add(num)){
            mButtons.get(num-1).setSelected(true);
        }

    }
    public void clearSum() {
        mChsets.clear();
        for (Button button : mButtons) {
            button.setSelected(false);
        }
    }

    public void removeSum(int sum) {
        if (mChsets.remove(sum)) {
            mButtons.get(sum-1).setSelected(false);
        }
    }

    public int getChannel() {
        return mChannel;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        try {
            mChannel = Integer.parseInt((String)getTag());
        } catch (Exception e) {
            e.printStackTrace();
        }

        final String inputName = SPUtils.getInstance(Context.MODE_PRIVATE).getString(KEY_INPUT+mChannel, null);
        if (inputName != null){
            mBtnInput.setText(inputName);
        }
        final String saveName = SPUtils.getInstance(Context.MODE_PRIVATE).getString(KEY_CHANNEL_NAME+mChannel, null);
        if (!TextUtils.isEmpty(saveName)){
            setChannelName(saveName);
        }else {
            setChannelName(mChName);
        }
        postInvalidate();
    }


    public void setChannelName(String name) {
        mChName = name;
        TextView tv = findViewById(R.id.ch_name);
        if (tv != null) {
            tv.setText(name);
        }
    }

    public boolean isFixed() {
        return isFixed;
    }

    public void setFixed(boolean fixed) {
        isFixed = fixed;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        int startX = (int) (mLineWidth);
        final int inputY = mBtnInput.getHeight() / 2;
        final int chY = (int) (mBtnCH.getY() + mBtnCH.getHeight() / 2);
        final int outputY = (int) (mBtnOutput.getY() + mBtnOutput.getHeight() / 2);
//        canvas.drawLine(startX,inputY, mBtnInput.getX(),inputY, mPaint );
        canvas.drawLines(new float[]{
                startX, inputY, mBtnInput.getX(), inputY,//top h1
                startX, chY, mBtnCH.getX(), chY,//mid h2
                startX, outputY, mBtnOutput.getX(), outputY ,//bottom h3
                startX, inputY - mLineWidth / 2, startX, outputY
        }, mPaint);

        canvas.drawLines(new float[]{

        }, mPaint);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public void initChecked(int[] high) {
        YzDebug.d("initChecked:"+ Arrays.toString(high));
        int index = 0;
        for (int i : high) {
            if (i == 1){
                mButtons.get(index).setSelected(true);
                mChsets.add(index);
            }else{
                mButtons.get(index).setSelected(false);
                mChsets.remove(index);
            }
            index++;
        }
    }

    private OnSummingChannelListener mOnSummingChannelListener;

    public void setOnSummingChannelListener(OnSummingChannelListener onSummingChannelListener) {
        mOnSummingChannelListener = onSummingChannelListener;
    }



    public interface OnSummingChannelListener{
        void onInputChanged(int channel, int index,  boolean isChecked);
        void onOutputChange(int channel, boolean isChecked);
    }
}
